package com.example.springboottestgit.controller.main;

/**
 * @description:
 * @author: ZZZ
 */


import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class ImageToVideoConverter {
    public static void convertImagesToVideo(String outputPath, String imageDir, int width, int height, double frameRate) throws Exception {
        File outputFile = new File(outputPath);
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, width, height);
        recorder.setFrameRate(frameRate);
        recorder.start();

        File[] files = new File(imageDir).listFiles();
//        Arrays.sort(files, new Comparator<File>() {
//            public int compare(File f1, File f2) {
//                long diff = f1.lastModified() - f2.lastModified();
//                if (diff > 0)
//                    return -1;
//                else if (diff == 0)
//                    return 0;
//                else
//                    return 1;//如果 if 中修改为 返回-1 同时此处修改为返回 1  排序就会是递减
//            }
//
//            public boolean equals(Object obj) {
//                return true;
//            }
//
//        });

        List<BufferedImage> images = new ArrayList<>();
        for (File file : files) {
            if (file.getName().endsWith(".jpg") || file.getName().endsWith(".png")) {
                System.out.println(file);
                images.add(ImageIO.read(file));
            }
        }

        Java2DFrameConverter converter = new Java2DFrameConverter();
        for (BufferedImage image : images) {
            Frame frame = converter.convert(image);
            recorder.record(frame);
            //frame.close();
        }

        recorder.stop();
        recorder.release();
    }

    public static void main(String[] args) {
        try {
            convertImagesToVideo("D:\\file\\video\\test\\test.mp4", "D:\\file\\video\\test", 640, 480, 30.0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}